<template>
  <div ref="chartRef"
       class="chart"
       :style="{ height, width }" />
</template>

<script lang="ts">
import { defineComponent, ref, unref, onMounted, onUnmounted, PropType, watch } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  props: {
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '800px',
    },
    title: {
      type: String as PropType<string>,
      default: '',
    },
    xAxisName: {
      type: String as PropType<string>,
      default: '位点',
    },
    yAxisName: {
      type: String as PropType<string>,
      default: 'map reads',
    },
    value: {
      type: Object as PropType<any>,
      default: {},
    },
    type: {
      type: String as PropType<string>,
      defaule: '',
    },
  },

  setup(props) {
    const chartRef = ref();
    let chartInstance: any = undefined;
    const option = {
      xAxis: {
        name: props.xAxisName,
        type: 'category',
        data: [],
        splitNumber: 30,
        axisLabel: {
          show: true,
        },
      },
      yAxis: {
        name: props.yAxisName,
        type: 'value',
        splitLine: {
          show: false,
        },
      },
      series: [],
    };

    onMounted(() => {
      chartInstance = echarts.init(unref(chartRef));
      Object.keys(props.value).forEach((item) => {
        let obj: any = {
          name: item,
          type: 'bar',
          data: props.value[item].y,
        };

        option.series.push(obj);
      });

      chartInstance.setOption(option);
      window.onresize = () => {
        chartInstance.resize();
      };
    });

    onUnmounted(() => {
      window.onresize = null;
    });

    watch(props, (val) => {
      let xAxis: any = [];

      Object.keys(props.value).forEach((item) => {
        xAxis = props.value[item].x;
        let obj: any = {
          name: item,
          type: 'bar',
          data: props.value[item].y,
        };
        option.series.push(obj);
      });

      Object.assign(option.xAxis, {
        data: xAxis,
      });
      chartInstance.setOption(option);
      window.onresize = () => {
        chartInstance.resize();
      };
    });

    return {
      chartRef,
    };
  },
});
</script>

<style lang="less" scoped>
/** chat 表格宽度自适应 */
.chart {
  :deep(div) {
    width: 100% !important;
  }

  :deep(canvas) {
    width: 100% !important;
  }
}
</style>